<script setup>
import { ref, reactive, toRaw, computed, onMounted, watch } from "vue";
import { getGlobal } from "/lib/utils/global.js";
const global = getGlobal();

const _teamInfoItemReg = {
  // 队长信息正则
  name: "",
  // 性别
  gender: "^(Male|Female|male|female)$",
  // 微信号
  wechat: "",
  // 邮箱
  email: "^\\w{3,}(\\.\\w+)*@[A-z0-9]+(\\.[A-z]{2,5}){1,10}$",
  // 高校名称
  school: "",
  // 专业名称
  major: "",
  // 年级
  grade: "",
};
const _teacherItemReg = {
  // 指导老师信息正则
  // 姓名
  name: "",
  // 性别
  gender: "^(Male|Female|male|female)$",
  // 手机号
  phone: `^1\\d{10}$`,
  // 邮箱
  email: "^\\w{3,}(\\.\\w+)*@[A-z0-9]+(\\.[A-z]{2,5}){1,10}$",
  // 高校名称
  school: "",
  // 职业名称
  job: "",
};

const _teamMemberItemReg = {
  // 姓名
  name: "",
  // 性别
  gender: "^(Male|Female|male|female)$",
  // 手机号
  phone: "^1\\d{10}$",
  // 邮箱
  email: "^\\w{3,}(\\.\\w+)*@[A-z0-9]+(\\.[A-z]{2,5}){1,10}$",
  // 高校名称
  school: "",
  // 专业名称
  major: "",
  // 年级
  grade: "",
};

const teamInfoItem = {
  // 队长信息
  name: "",
  // 性别
  gender: "",
  // 微信号
  wechat: "",
  // 邮箱
  email: "",
  // 高校名称
  school: "",
  // 专业名称
  major: "",
  // 年级
  grade: "",
};

const teacherItem = {
  // 指导老师信息
  // 姓名
  name: "",
  // 性别
  gender: "",
  // 手机号
  phone: "",
  // 邮箱
  email: "",
  // 高校名称
  school: "",
  // 职业名称
  job: "",
};
// 团队队员信息
const teamMemberItem = {
  // 姓名
  name: "",
  // 性别
  gender: "",
  // 手机号
  phone: "",
  // 邮箱
  email: "",
  // 高校名称
  school: "",
  // 专业名称
  major: "",
  // 年级
  grade: "",
};

const formData = reactive({
  agree: "", // 是否同意
  type: "", // 团队想要参加的类型 [1 花旗挑战 0 自选赛道]
  teamType: "", // 哪种 [1 人工智能-风险控制 2 VE（虚拟经济）]
  esgName: "", // ESG 项目名称
  vEName: "", // Vitual Economy项目名称
  projectName: "", // 项目名称
  teamName: "", // 团队名称
  teamPhone: "", // 团队队长手机号
  teamInfo: [{ ...teamInfoItem }],
  // 指导老师信息
  teacher: [{ ...teacherItem }],
  // 团队队员
  teamMember: [{ ...teamMemberItem }, { ...teamMemberItem }],
});

function addTeacher() {
  formData.teacher.push({ ...teacherItem });
}

function addTamMember() {
  formData.teamMember.push({ ...teamMemberItem });
}

// 本地缓存
watch(formData, (n) => {
  localStorage.setItem("formDataStore__HQB", JSON.stringify(n));
});

const formRef = ref(null);
const rawForm = toRaw(formData);
const qrcode_url = window.qrcode_url;
const csrf_token = window.csrf_token;
const formAction = window.formAction;
const formDefaultData = window.formDefaultData;

const showModal = ref(false);
function closeModal() {
  showModal.value = false;
}

function submit() {
  if (!checkForm()) {
    return;
  }
  formRef.value.submit();
}

const disabled = window.formDefaultData;
onMounted(async () => {
  if (formDefaultData) {
    Object.assign(formData, JSON.parse(formDefaultData));

    showModal.value = true;
    return;
  }
  const _formDataStore = localStorage.getItem("formDataStore__HQB");
  const formDataJson = JSON.parse(_formDataStore);
  if (_formDataStore) {
    const confirm = await global.$pop.alert({
      btn: ["confirm", "cancel"],
      content:
        "You have partially completed the required information. <br/>Would you like to proceed？",
    });
    if (confirm) {
      Object.assign(formData, formDataJson);
    }
  }
});

const rawFormRef = ref();
function checkForm() {
  if (!rawFormRef.value.checkValidity()) {
    return false;
  }
  return true;
}
</script>

<template>
  <div class="h-16 bg-blue-100"></div>

  <div class="p-4 bg-white">
    <div class="py-4 text-2xl text-center text-sky-500">
      2023-2024 19th Citi Financial Innovation Application Competition
      Registration Form
    </div>
    <div class="pb-4 border-b">
      Dear students, Welcome to register for the 2023-2024 19th Citi Financial
      Innovation Application Competition! We urge you to ensure that all
      information provided in this registration form is accurate and complete.
      Please fill this form out carefully, and we thank you in advance for your
      diligence and cooperation.
    </div>
    <form ref="rawFormRef" action="#" onsubmit="return false">
      <div class="py-4 space-y-8">
        <section>
          <div>
            1.. Please confirm whether you agree to disclose relevant personal
            information to the Citi Cup Organizing Committee. By registering,
            you authorize the Organizing Committee to process the relevant
            personal information as necessary for the purpose of the Citi Cup
            Competition.
            <div class="py-2 text-sm font-bold text-red-500">
              Note: Without your confirmation and authorization, we regret that
              we cannot validate your registration. (The personal information
              collected is only for the purposes of this competition
              registration and contact matters, and will not be disclosed to the
              public)
            </div>
          </div>
          <div class="flex flex-col">
            <label
              class="flex items-center gap-2 p-2 cursor-pointer text-slate-500 hover:bg-slate-50"
              ><input
                name="a"
                required
                :disabled="disabled"
                class="form-radio form-radio-user"
                type="radio"
                v-model="formData.agree"
                value="1"
              />
              YES</label
            >
            <label
              class="flex items-center gap-2 p-2 cursor-pointer text-slate-500 hover:bg-slate-50"
              ><input
                name="a"
                required
                :disabled="disabled"
                class="form-radio form-radio-user"
                type="radio"
                v-model="formData.agree"
                value="0"
              />
              NO</label
            >
          </div>
        </section>

        <section>
          <div>2.Please indicate your team's competition preference:</div>
          <div class="flex flex-col">
            <label
              class="flex items-center gap-2 p-2 cursor-pointer text-slate-500 hover:bg-slate-50"
              ><input
                name="b"
                required
                :disabled="disabled"
                class="form-radio form-radio-user"
                type="radio"
                v-model="formData.type"
                value="1"
              />
              Citi Challenges</label
            >
            <label
              class="flex items-center gap-2 p-2 cursor-pointer text-slate-500 hover:bg-slate-50"
              ><input
                name="b"
                required
                :disabled="disabled"
                class="form-radio form-radio-user"
                type="radio"
                v-model="formData.type"
                value="0"
              />
              Self-selected track focusing on Financial IT-related topics</label
            >
          </div>
        </section>

        <section v-if="formData.type != '' && formData.type != '0'">
          <div>3.Which Citi challenge topic will your team participate in:</div>
          <div class="flex flex-col">
            <label
              class="flex items-center gap-2 p-2 cursor-pointer text-slate-500 hover:bg-slate-50"
              ><input
                :disabled="disabled"
                class="form-radio form-radio-user"
                type="radio"
                v-model="formData.teamType"
                value="1"
              />
              AI – Risk Control</label
            >
            <label
              class="flex items-center gap-2 p-2 cursor-pointer text-slate-500 hover:bg-slate-50"
              ><input
                :disabled="disabled"
                class="form-radio form-radio-user"
                type="radio"
                v-model="formData.teamType"
                value="0"
              />
              AI – Hallucination
            </label>
          </div>
        </section>

        <section
          v-if="
            formData.type != '' &&
            formData.type != '0' &&
            formData.teamType == '1'
          "
        >
          <div>
            4.Your team's project name is (Citi Challenge - AI – Risk Control)
          </div>
          <div class="flex flex-col mt-2">
            <input
              pattern="^[\u4E00-\u9FA5A-Za-z0-9—\.\-]+$"
              :disabled="disabled"
              type="text"
              v-model="formData.esgName"
              class="form-input form-input-user"
            />
          </div>
        </section>

        <section
          v-if="
            formData.type != '' &&
            formData.type != '0' &&
            formData.teamType == '0'
          "
        >
          <div>
            5.Your team's project name is (Citi Challenge - AI – Hallucination)
          </div>
          <div class="flex flex-col mt-2">
            <input
              pattern="^[\u4E00-\u9FA5A-Za-z0-9—\.\-]+$"
              :disabled="disabled"
              type="text"
              v-model="formData.vEName"
              class="form-input form-input-user"
            />
          </div>
        </section>

        <section v-if="formData.type == '0'">
          <div>
            6.Your team's project name is (Self-selected track focusing on
            Financial IT-related topics)
          </div>
          <div class="flex flex-col mt-2">
            <input
              required
              pattern="^[\u4E00-\u9FA5A-Za-z0-9—\.\-]+$"
              :disabled="disabled"
              type="text"
              v-model="formData.projectName"
              class="form-input form-input-user"
            />
          </div>
        </section>

        <section>
          <div>7.What is your team's name:</div>
          <div class="flex flex-col mt-2">
            <input
              required
              pattern="^[\u4E00-\u9FA5A-Za-z0-9—\.\-]+$"
              :disabled="disabled"
              type="text"
              v-model="formData.teamName"
              class="form-input form-input-user"
            />
          </div>
        </section>

        <section>
          <div>
            8.What is the mobile phone number of your team leader:
            <div class="text-sm text-slate-500">
              This mobile phone number will be used as the verification number
              for subsequent modifications to the team roster, please fill it in
              carefully.
              <b class="text-red-500"
                >(Note: You must fill in a mainland China mobile number.)</b
              >
            </div>
          </div>
          <div class="flex flex-col mt-2">
            <input
              required
              pattern="^1\d{10}$"
              :disabled="disabled"
              type="text"
              v-model="formData.teamPhone"
              class="w-1/2 form-input form-input-user"
            />
          </div>
        </section>

        <section>
          <div>9.Team Leader Information</div>
          <div class="flex flex-col mt-2 overflow-auto">
            <table class="table-scroll">
              <thead class="thead">
                <tr>
                  <th class="w-12"></th>
                  <th>Name</th>
                  <th>Gender</th>
                  <th>WeChat ID</th>
                  <th>Email Address</th>
                  <th>University Affiliation</th>
                  <th>Major</th>
                  <th>Grade (e.g., Undergraduate Year 3)</th>
                </tr>
              </thead>
              <tbody class="tbody">
                <tr v-for="(d, i) in formData.teamInfo" :key="i">
                  <td class="w-12 bg-slate-100">Team Leader</td>
                  <td v-for="(m, n) in d" :key="n">
                    <input
                      required
                      :pattern="
                        _teamInfoItemReg[n] || `^[\u4E00-\u9FA5A-Za-z0-9]+$`
                      "
                      :disabled="disabled"
                      type="text"
                      class="w-full px-4 py-2 transition border-none outline-none focus:ring-1 focus:ring-blue-500"
                      v-model="formData.teamInfo[i][n]"
                    />
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </section>

        <section>
          <div>
            10.Academic advisor Information
            <div class="text-sm text-slate-500">
              (Each team must choose at least one academic advisor, but no more
              than two)
            </div>
          </div>
          <div class="flex flex-col mt-2 overflow-auto">
            <table class="table-scroll">
              <thead class="thead">
                <tr>
                  <th class="w-12"></th>
                  <th>Name</th>
                  <th>Gender</th>
                  <th>Mobile Number</th>
                  <th>Email Address</th>
                  <th>Name of the university currently employed at</th>
                  <th>Position</th>
                </tr>
              </thead>
              <tbody class="tbody">
                <tr v-for="(d, i) in formData.teacher" :key="i">
                  <td
                    class="flex items-center justify-center w-12 bg-slate-100"
                  >
                    <span
                      class="w-full text-white bg-red-500 border rounded cursor-pointer hover:bg-red-400"
                      v-if="i > 0"
                      @click="formData.teacher.splice(i, 1)"
                      >－</span
                    >
                    <span v-else>{{ i + 1 }}</span>
                  </td>
                  <td v-for="(m, n) in d" :key="n">
                    <input
                      required
                      :pattern="
                        _teacherItemReg[n] || `^[\u4E00-\u9FA5A-Za-z0-9]+$`
                      "
                      :disabled1="disabled"
                      type="text"
                      class="w-full px-4 py-2 transition border-none outline-none focus:ring-1 focus:ring-blue-500"
                      v-model="formData.teacher[i][n]"
                    />
                  </td>
                </tr>
              </tbody>
            </table>
          </div>

          <div
            class="flex items-center justify-center mt-4"
            v-if="formData.teacher.length < 2"
          >
            <span
              class="flex items-center gap-2 p-2 px-8 border rounded cursor-pointer text-slate-500 hover:bg-slate-100"
              @click="addTeacher"
            >
              <span
                class="flex items-center justify-center w-5 h-5 text-white bg-blue-500 rounded-full"
                >＋</span
              >
              Add
            </span>
          </div>
        </section>

        <section>
          <div>
            11.Team Member Information
            <div class="text-sm text-slate-500">
              (Each team, in addition to the team leader, must include at least
              2 members)
            </div>
          </div>
          <div class="flex flex-col mt-2 overflow-auto">
            <table class="table-scroll">
              <thead class="thead">
                <tr>
                  <th class="w-12"></th>
                  <th>Name</th>
                  <th>Gender</th>
                  <th>Mobile Number</th>
                  <th>Email Address</th>
                  <th>University Affiliation</th>
                  <th>Major</th>
                  <th>Grade (e.g., Undergraduate Year 3)</th>
                </tr>
              </thead>
              <tbody class="tbody">
                <tr v-for="(d, i) in formData.teamMember" :key="i">
                  <td
                    class="flex items-center justify-center w-12 bg-slate-100"
                  >
                    <span
                      class="w-full text-white bg-red-500 border rounded cursor-pointer hover:bg-red-400"
                      v-if="i > 1"
                      @click="formData.teamMember.splice(i, 1)"
                      >－</span
                    >
                    <span v-else>{{ i + 1 }}</span>
                  </td>
                  <td v-for="(m, n) in d" :key="n">
                    <input
                      required
                      :pattern="
                        _teamMemberItemReg[n] || `^[\u4E00-\u9FA5A-Za-z0-9]+$`
                      "
                      type="text"
                      class="w-full px-4 py-2 transition border-none outline-none focus:ring-1 focus:ring-blue-500"
                      v-model="formData.teamMember[i][n]"
                    />
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
          <div
            class="flex items-center justify-center mt-4"
            v-if="formData.teamMember.length >= 2"
          >
            <span
              class="flex items-center gap-2 p-2 px-8 border rounded cursor-pointer text-slate-500 hover:bg-slate-100"
              @click="addTamMember"
            >
              <span
                class="flex items-center justify-center w-5 h-5 text-white bg-blue-500 rounded-full"
                >＋</span
              >
              Add
            </span>
          </div>
        </section>

        <div class="sticky bottom-0 pt-20 pb-8 text-center">
          <button
            class="px-20 py-3 m-auto text-white transition bg-blue-500 rounded hover:bg-blue-600"
            @click="submit"
          >
            Submit
          </button>
        </div>
      </div>
    </form>

    <!-- 真正 POST 提交 -->
    <form
      ref="formRef"
      class="flex items-center justify-center mt-12"
      method="post"
      :action="formAction"
    >
      <input
        class="border"
        type="hidden"
        name="_csrf_token"
        :value="csrf_token"
      />
      <input
        name="formData"
        type="hidden"
        class="w-full border"
        :value="JSON.stringify(rawForm)"
      />
    </form>
  </div>

  <!-- 测试信息，打包后删除 -->
  <div class="sticky bottom-0 hidden px-4 mt-4 text-white bg-black/50">
    <div class="font-medium">formAction: {{ formAction }}</div>
    <div class="font-medium">csrf_token: {{ csrf_token }}</div>
    <div class="p-2 bg-red-400/50">
      formData
      <div class="p-2 border border-red-300">
        {{ formData }}
      </div>
    </div>
  </div>

  <!-- 报名成功后弹出的二维码 -->
  <div
    class="fixed top-0 left-0 flex items-center justify-center w-full h-full p-8 bg-black/50"
    v-if="showModal"
  >
    <div class="relative bg-white rounded">
      <div class="p-4 text-center text-slate-600">
        Your answer sheet has been submitted. Please have the
        <b class="font-bold text-slate-800">team captain</b>scan the QR code
        below to enter the competition group!
      </div>
      <div class="p-4">
        <img
          :src="qrcode_url"
          class="object-contain p-2 m-auto border rounded border-black/5 bg-black/5 w-52 md:w-80"
        />
      </div>

      <div
        class="absolute cursor-pointer top-[calc(100%+20px)] left-0 w-full flex justify-center"
        @click="closeModal"
      >
        <span
          class="text-5xl transition text-white/80 hover:text-white hover:scale-110"
          >×</span
        >
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.form-radio-user {
  @apply border-gray-300 text-blue-600 shadow-sm focus:border-blue-300 focus:ring focus:ring-offset-0 focus:ring-blue-200 focus:ring-opacity-50;
}

.form-input-user {
  @apply border-gray-300 shadow-sm focus:border-blue-300 focus:ring focus:ring-offset-0 focus:ring-blue-200 focus:ring-opacity-50 rounded transition;
}

.table-scroll {
  @apply text-sm text-center text-slate-500;

  .thead {
    @apply bg-slate-100;
  }

  .tbody {
    @apply bg-white;
  }

  th,
  td {
    @apply border;

    &:first-child {
      @apply sticky left-0 whitespace-nowrap p-2;
    }
  }

  th {
    @apply text-slate-500 whitespace-nowrap py-2 px-6;
  }

  td {
  }
}
</style>
